package com.mos.iot.mqtt.listener.annotation;

import com.mos.iot.mqtt.listener.MqttTopicListenerManager;
import com.mos.iot.mqtt.listener.MqttTopicMethodManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.List;

@Slf4j
public class MqttAnnotationScanner implements BeanPostProcessor {

    private final List<Class<? extends Annotation>> annotations = Collections.singletonList(MqttInput.class);

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        ReflectionUtils.doWithMethods(bean.getClass(),
                method -> {
                    MqttInput input = method.getAnnotation(MqttInput.class);
                    for (String topic : input.topics()) {
                        MqttTopicListenerManager.addListener(input.clientId(), topic, bean, method);
                    }
                    MqttTopicMethodManager.add(method);
                },
                method -> {
                    for (Class<? extends Annotation> annotationClass : annotations) {
                        if (method.isAnnotationPresent(annotationClass)) {
                            log.info("{}注册监听器 -> {}", beanName, method.getName());
                            return true;
                        }
                    }
                    return false;
                });
        return bean;
    }

}
